package algorithm.unionfind;

public class UnionFindSize extends AbstractUnionFind {


    private int[] sz;

    public UnionFindSize(int capacity) {
        super(capacity);
        sz = new int[capacity];
        for (int i = 0; i < capacity; i++) {
            sz[i] = 1;
        }
    }


    @Override
    public int find(int p) {
        while (p != data[p]) {
            p = data[p];
        }
        return p;
    }



    @Override
    public void union(int p, int q) {
        int pRoot = find(p);
        int qRoot = find(q);

        if (pRoot == qRoot) {
            return;
        }
        //判断哪个size，则以哪个为主
        if (sz[pRoot]<sz[qRoot]){
            data[pRoot] = qRoot;
            sz[qRoot]+=sz[pRoot];
        }else{
            data[qRoot] = pRoot;
            sz[pRoot]+=sz[qRoot];
        }
    }
}
